<template>
  <div class="app-container">
    <!--搜索区域-->
    <el-form size="mini" :inline="true" :model="searchForm">
      <el-form-item>
        <el-input v-model="searchForm.name" placeholder="角色名称" @keyup.enter.native="handleSearch"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch" :loading="searchButtonLoading">查询
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" icon="el-icon-plus" @click="showDialogForm()">添加</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="danger" icon="el-icon-delete" @click="handleDelete()">删除</el-button>
      </el-form-item>
    </el-form>
    <!--表格区域-->
    <el-table border size="mini" v-loading="tableLoading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column label="ID" prop="id" type="selection"></el-table-column>
      <el-table-column label="ID" prop="id"></el-table-column>
      <el-table-column label="名称" prop="name"></el-table-column>
      <el-table-column label="备注" prop="remarks"></el-table-column>
      <el-table-column label="状态" prop="status">
        <template slot-scope="role">
          <el-tag :type="role.row.status === 0 ? 'success' : 'danger'" size="mini">
            {{role.row.status === 0 ? '启用' : '停用'}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建人" prop="createBy"></el-table-column>
      <el-table-column label="更新人" prop="updateBy"></el-table-column>
      <el-table-column label="创建时间" prop="createTime" :formatter="createTimeFormatter" width="135"></el-table-column>
      <el-table-column label="更新时间" prop="updateTime" :formatter="updateTimeFormatter" width="135"></el-table-column>
      <el-table-column label="操作" width="70">
        <template slot-scope="scope">
          <el-tooltip content="编辑" placement="top">
            <i class="el-icon-edit" @click="showDialogForm(scope.row)" style="cursor: pointer"></i>
          </el-tooltip>
          <el-tooltip content="授权" placement="top">
            <i class="el-icon-thumb" @click="showPermissionDialog(scope.row.id)" style="cursor: pointer"></i>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <i class="el-icon-delete" @click="handleDelete(scope.row.id)" style="cursor: pointer"></i>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <el-pagination :current-page="currentPage"
                   :page-size="pageSize"
                   :total="total"
                   :page-sizes="[10, 20, 50, 100]"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"
                   layout="prev, pager, next, sizes, total"
                   background></el-pagination>
    <!--模态框-->
    <el-dialog :title="dialogTitle"
               :visible.sync="dialogVisible"
               center
               width="350px"
               :close-on-press-escape="false"
               :close-on-click-modal="false">
      <el-form size="mini" :model="dialogForm" :rules="dialogRules" status-icon ref="dialogForm">
        <el-form-item label="名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="dialogForm.name" autocomplete="off" placeholder="角色名称"></el-input>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth" prop="remarks">
          <el-input v-model="dialogForm.remarks" autocomplete="off" placeholder="角色备注"></el-input>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth" prop="status">
          <el-select v-model="dialogForm.status" placeholder="请选择角色状态">
            <el-option label="启用" :value="0"></el-option>
            <el-option label="停用" :value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" size="mini" @click="handleEdit('dialogForm')" :loading="dialogButtonLoading">确 定
        </el-button>
      </div>
    </el-dialog>
    <!--授权模态框-->
    <el-dialog title="授权"
               :visible.sync="permissionDialogVisible"
               center
               width="350px"
               :close-on-press-escape="false"
               :close-on-click-modal="false">
      <el-tree :data="permissionData"
               show-checkbox default-expand-all
               :props="defaultProps"
               node-key="id"
               ref="tree"
               :default-checked-keys="roleHaveIds"></el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="permissionDialogVisible = false">取 消</el-button>
        <el-button type="primary" size="mini" @click="handleSubmit" :loading="dialogButtonLoading">确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listRole, editRole, deleteRole, getTree, authorize } from '@/api/role'
  import { formatDate } from '@/utils/cliUtils'

  export default {
    name: 'index',
    data() {
      return {
        list: null,
        tableLoading: true,
        searchForm: {
          name: ''
        },
        searchButtonLoading: false,
        currentPage: 1,
        pageSize: 10,
        total: 0,
        dialogVisible: false,
        dialogTitle: '',
        dialogForm: {
          id: '',
          name: '',
          remarks: '',
          status: ''
        },
        formLabelWidth: '60px',
        dialogRules: {
          name: [
            { required: true, message: '请输入角色名称', trigger: 'blur' }
          ],
          remarks: [
            { required: true, message: '请输入角色备注', trigger: 'blur' }
          ],
          status: [
            { required: true, message: '请输入角色状态', trigger: 'blur' }
          ]
        },
        dialogButtonLoading: false,
        multipleSelection: [],
        ids: '',
        permissionDialogVisible: false,
        permissionData: [],
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        roleHaveIds: [],
        roleId: '',
        permissionIds: ''
      }
    },
    created() {
      this.fetchData()
    },
    methods: {
      fetchData() {
        this.tableLoading = true
        listRole({ pageNum: this.currentPage, pageSize: this.pageSize, name: this.searchForm.name }).then(response => {
          this.list = response.data
          this.total = response.total
          this.tableLoading = false
          this.searchButtonLoading = false
        }).catch(() => {
          this.tableLoading = false
          this.searchButtonLoading = false
        })
      },
      createTimeFormatter(row) {
        let date = new Date(row.createTime)
        return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
      },
      updateTimeFormatter(row) {
        let date = new Date(row.updateTime)
        return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
      },
      handleSearch() {
        this.searchButtonLoading = true
        this.fetchData()
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.fetchData()
      },
      showDialogForm(row) {
        this.dialogVisible = true
        if (row == undefined) {
          this.dialogTitle = '添加角色'
          this.dialogForm.id = ''
          this.dialogForm.name = ''
          this.dialogForm.remarks = ''
          this.dialogForm.status = ''
        } else {
          this.dialogTitle = '更新角色'
          this.dialogForm.id = row.id
          this.dialogForm.name = row.name
          this.dialogForm.remarks = row.remarks
          this.dialogForm.status = row.status
        }
      },
      handleEdit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.dialogButtonLoading = true
            editRole(this.dialogForm).then(response => {
              this.$message({ type: 'success', message: response.msg })
              this.dialogVisible = false
              this.fetchData()
              this.dialogButtonLoading = false
            }).catch(() => {
              this.dialogButtonLoading = false
            })
          } else {
            return false
          }
        })
      },
      handleDelete(id) {
        this.ids = ''
        if (id !== undefined) {
          this.ids = id
        } else {
          for (let i = 0; i < this.multipleSelection.length; i++) {
            this.ids += this.multipleSelection[i] + ','
          }
        }
        console.log(this.ids)
        this.$confirm('确定要删除吗？', '提示', {
          type: 'warning',
          cancelButtonText: '取消',
          confirmButtonText: '确认',
          closeOnPressEscape: false,
          closeOnClickModal: false
        }).then(() => {
          deleteRole({ ids: this.ids }).then(response => {
            this.$message({ type: 'success', message: response.msg })
            this.fetchData()
          }).catch(() => {
          })
        }).catch(() => {
          // 选择了取消操作
        })
      },
      handleSelectionChange(val) {
        for (let i = 0; i < val.length; i++) {
          if (this.multipleSelection.indexOf(val[i].id) === -1) {
            this.multipleSelection.push(val[i].id)
          }
        }
      },
      showPermissionDialog(roleId) {
        this.roleId = roleId
        this.permissionDialogVisible = true
        getTree({ roleId: roleId }).then(response => {
          this.permissionData = response.data
          this.roleHaveIds = response.roleHaveIds
        }).catch(() => {

        })
      },
      handleSubmit() {
        this.permissionIds = ''
        let keys = this.$refs.tree.getCheckedKeys()
        for (let i = 0; i < keys.length; i++) {
          this.permissionIds += keys[i] + ','
        }
        authorize({ roleId: this.roleId, permissionIds: this.permissionIds }).then(response => {
          this.$message({ type: 'success', message: response.msg })
          this.permissionDialogVisible = false
        }).catch(() => {
          this.permissionDialogVisible = false
        })
      }
    }
  }
</script>

<style scoped lang="scss">
  .el-pagination {
    margin-left: -10px;
    margin-top: 5px;
  }

  .el-select {
    width: 100%;
  }
</style>
